package io.github.jieblog.juc.day8;

import java.util.Random;
import java.util.concurrent.*;

/**
 * jie
 * 2017-06-2017/6/18
 */
public class TheadLocalLearn {
    public static final int GEN_COUNT = 10000000;
    public static final int THEARD_COUNT = 4;
    static ExecutorService executorService = Executors.newFixedThreadPool(THEARD_COUNT);
    public static Random random = new Random(123);
    public static ThreadLocal<Random> randomThreadLocal = new ThreadLocal<Random>() {
        @Override
        protected Random initialValue() {
            return new Random(123);
        }
    };

    public static class RndTask implements Callable<Long> {
        private int type = 0;

        public RndTask(int type) {
            this.type = type;
        }

        public Random getRandom() {
            if (type == 0) {
                return random;
            } else {
                return randomThreadLocal.get();
            }
        }

        @Override
        public Long call() throws Exception {
            long startTime = System.currentTimeMillis();
            for (int i = 0; i < GEN_COUNT; i++) {
                getRandom().nextInt();
            }
            long endTime = System.currentTimeMillis();
            return endTime - startTime;
        }
    }

    public static void main(String[] args) throws ExecutionException, InterruptedException {
        Future<Long>[] futures = new Future[THEARD_COUNT];
        for (int i = 0; i < THEARD_COUNT; i++) {
            Future<Long> future = executorService.submit(new RndTask(0));
            futures[i] = future;
        }

        int sum1 = 0;
        for (int i = 0; i < THEARD_COUNT; i++) {
            sum1 += futures[i].get();
        }
        System.out.println(sum1);


        for (int i = 0; i < THEARD_COUNT; i++) {
            Future<Long> future = executorService.submit(new RndTask(2));
            futures[i] = future;
        }

        int sum2 = 0;
        for (int i = 0; i < THEARD_COUNT; i++) {
            sum2 += futures[i].get();
        }
        System.out.println(sum2);
    }

}

